// src/decorators/is-email-or-empty.decorator.ts
import {
    registerDecorator,
    ValidationArguments,
    ValidationOptions,
    ValidatorConstraint,
    ValidatorConstraintInterface
} from "class-validator";

@ValidatorConstraint({ name: "IsEmailOrEmptyString", async: false })
export class IsEmailOrEmptyStringConstraint implements ValidatorConstraintInterface {
    validate(value: any, _args: ValidationArguments) {
        // 允许空字符串
        if (value === "") return true;

        // 验证邮箱格式（简易正则，可根据需求调整）
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return typeof value === "string" && emailRegex.test(value);
    }

    defaultMessage(args: ValidationArguments) {
        return `${args.property} must be a valid email or an empty string.`;
    }
}

/**
 * 自定义邮箱 class-validator 验证装饰器，增强 IsEmail 功能，允许空字符串
 * @param validationOptions 验证选项
 * @returns {Function} 装饰器函数
 */
export function IsEmailOrEmptyString(validationOptions?: ValidationOptions) {
    return function (object: object, propertyName: string) {
        registerDecorator({
            target: object.constructor,
            propertyName: propertyName,
            options: validationOptions,
            constraints: [],
            validator: IsEmailOrEmptyStringConstraint
        });
    };
}

// export class UpdateDepartmentDto {
//     @Transform(({ value }) => (typeof value === "string" ? value.trim() : value)) // 处理前后空格
//     @IsOptional()
//     @IsEmailOrEmpty({ message: "邮箱格式无效或必须为空字符串" }) // 使用自定义装饰器
//     @ApiProperty({ required: false, example: "xxx@xxx.xxx" })
//     email: string;
// }
